<?php
namespace adminv1;

use Yii;
use yii\web\Response;
use admin\models\auth\User;
use common\utils\Model;


/**
 * 接口基础处理
 * @author Administrator
 * @param  所有版本接口的控制器父类
 */
class CoreController extends \yii\rest\ActiveController
{
    public  $modelClass = '';
    private $http_id;
    public  $_user;  //用户信息
    public  $_uid;
    public  $request;
    public $curDateTime;

    public function beforeAction($action)
    {
        $this->request = array_merge(
			Yii::$app->request->post(),
			Yii::$app->request->get(),
			$_FILES
		);
        $this->curDateTime = date("Y-m-d H:i:s");

        $mod = ['no-auth', 'common'];
        $actionMod = ['reg','login','test', 'export'];
        $controller = Yii::$app->controller->id;
        $actionName = Yii::$app->controller->action->id;

        if(in_array($controller, $mod) || in_array($actionName, $actionMod)) return true;



        if(!isset($this->request['auth_key'])) return $this->error('auth_key is null.','200','404');

        $this->_user = User::loginByAuthkey(['auth_key' => $this->request['auth_key']]);

        if(empty($this->_user)) return $this->error('用户不存在', '200', '404');
        $this->_uid = $this->_user['id'];

        ## 接口权限验证
        if(\Yii::$app->params['apiAuth']) {
            $apiAuth = \Yii::$app->cache->get('userApiCache_'.$this->_uid);
            if(!$apiAuth) $apiAuth =  [];
            $apiAuth = array_merge($apiAuth, \Yii::$app->params['ignore_api']);

            if(!in_array('v1/'.$controller.'/'.$actionName, $apiAuth)){
                $this->error('你没有此权限,请联系管理员','200','403');
                return false;
            }
        }
        return true;
    }

    public function request($key,$default='')
    {
        $request = array_merge(Yii::$app->request->post(), Yii::$app->request->get(), $_FILES);
        return isset($request[$key]) ? $request[$key] : $default;
    }


    public function success($msg='', $res = [], $extend = []) {
        $data = [
            'status' => "200"  ,
            'code'   => 0,
            'msg'    => (string)$msg,
            'data'   => $res,
        ];
        if($extend) $data['extend'] = $extend;
       return $this->send($data);
    }

    public function error($msg='', $status = '200', $code = 1){
        $data = [
            'status'=> $status."",
            'code'  => $code,
            'msg'   => (string)$msg,
        ];
        return  $this->send($data);
    }

    public function send($data = [])
    {
        $out = json_encode($data, JSON_UNESCAPED_UNICODE);
        die($out);
    }


}

?>


